<template>
  <div class="main_spac1 maincl">
    <div class="main_white padding10">
      <div class="main_crumbs boxdq">
        <div class="main_crumbs_l">
          <a href="javascript:;" @click="$router.back(-1)">
            <i class="el-icon-arrow-down"></i>返回
          </a>
          <em>|</em>
          <span>分组管理</span>
        </div>
        <div class="main_crumbs_rt box"></div>
      </div>
      <div class="mainor_form" style="margin-top:15px">
        <el-form
          :inline="true"
          :model="form"
          class="demo-form-inline"
          ref="userListFrom"
          label-width="60px"
        >
          <el-form-item label="名称：" prop="name">
            <el-input
              v-model.trim="form.name"
              placeholder="名称"
              clearable
              class="wid220"
            ></el-input>
          </el-form-item>
          <el-form-item label="分类：" prop="category_id" class="wid220">
            <el-cascader
              v-model="form.category_id"
              :options="options"
              :props="defaultProps"
            ></el-cascader>
          </el-form-item>
          <MainFormBtn @reset="reset" @getSearchFor="getArticleList" :loading="listLoading" :showBtn="false" />
        </el-form>
      </div>
      <div class="main-controls-wrap">
        <div>
          <el-button class="mainor_tea" @click="shield = true"
            >筛选商品</el-button
          >
          <el-button class="mainor_tea" @click="importDialog()"
            >导入商品</el-button
          >
          <el-button @click="empty" v-repeatClick>清空</el-button>
          <el-button @click="batch" v-repeatClick>批量删除</el-button>
        </div>
      </div>
      <div class="main_table" style="min-height: 660px">
        <el-table
          ref="multipleTable"
          v-loading="listLoading"
          :data="list.list.data"
          element-loading-text="加载中"
          fit
          border
          highlight-current-row
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" />
          <el-table-column
            label="名称"
            prop="goods[0].name"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="别名"
            prop="goods[0].byname"
            :show-overflow-tooltip="true"
          />
          <el-table-column label="图片" class-name="main_hei">
            <template slot-scope="scope">
              <div class="demo-image__error mainor_im">
                <el-image
                  fit="fill"
                  :src="scope.row.pic"
                  :preview-src-list="scope.row.pics"
                >
                  <div slot="error" class="image-slot">
                    <img :src="puzzleImg" />
                  </div>
                </el-image>
              </div>
            </template>
          </el-table-column>
          <el-table-column
            label="分类"
            prop="userNickname"
            :show-overflow-tooltip="true"
          >
            <template slot-scope="scope"
              >{{
                scope.row.goods[0].category_p
                  ? scope.row.goods[0].category_p.title
                  : ""
              }}|{{
                scope.row.goods[0].category
                  ? scope.row.goods[0].category.title
                  : ""
              }}</template
            >
          </el-table-column>
          <el-table-column
            label="编码"
            prop="goods[0].goods_code"
            :show-overflow-tooltip="true"
          />
          <el-table-column
            label="状态"
            prop="status"
            :show-overflow-tooltip="true"
            width="120"
            class-name="main_hei"
          >
            <template slot-scope="scope">{{
              scope.row.goods[0].status == 1 ? "上架" : "下架"
            }}</template>
          </el-table-column>
        </el-table>
      </div>
      <div class="main_page boxdq">
        <div></div>
        <!-- 分页 -->
        <div class="main_page_r">
          <MainPagination
            :current-page="current.page"
            :page-sizes="[20, 30, 50, 100]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            background
            @size-change="changeLimit"
            @current-change="changePage"
          />
        </div>
      </div>

      <el-dialog
        title="请选择屏蔽商品"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        @close="close"
        :visible.sync="shield"
        class="main_dialog dialog900 small-padding-dialog"
      >
        <div class="mainor_form batch-wrap">
          <el-form
            :inline="true"
            :model="form_sh"
            class="demo-form-inline"
            ref="userListFrom1"
            label-width="10px"
          >
            <el-form-item label prop="category_id" class="wid180">
              <el-cascader
                v-model="form_sh.category_id"
                :options="options"
                :props="defaultProps"
                placeholder="分类"
              ></el-cascader>
            </el-form-item>
            <el-form-item label=" " prop="name">
              <el-input
                v-model.trim="form_sh.name"
                placeholder="名称"
                clearable
                class="wid180"
              ></el-input>
            </el-form-item>
          </el-form>
          <div>
            <el-button
              class="reset mg-r-6"
              type="primary"
              @click="$refs['userListFrom1'].resetFields()"
              >重置</el-button
            >
            <el-button
              type="primary"
              @click="getArticleList"
              :loading="listLoading"
              >搜索</el-button
            >
          </div>
        </div>
        <div class="main_table mg-t-6">
          <el-table
            ref="multipleTable1"
            v-loading="listLoading"
            :data="list_sh.list.data"
            element-loading-text="加载中"
            fit
            border
            highlight-current-row
            max-height="500"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" />
            <el-table-column
              label="名称"
              prop="name"
              :show-overflow-tooltip="true"
            />
            <el-table-column
              label="别名"
              prop="byname"
              :show-overflow-tooltip="true"
            />
            <el-table-column label="图片" width="120" class-name="main_hei">
              <template slot-scope="scope">
                <div class="demo-image__error mainor_im">
                  <el-image
                    fit="fill"
                    :src="scope.row.pic"
                    :preview-src-list="scope.row.pics"
                  >
                    <div slot="error" class="image-slot">
                      <img :src="puzzleImg" />
                    </div>
                  </el-image>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              label="分类"
              prop="userNickname"
              width="180"
              :show-overflow-tooltip="true"
            >
              <template slot-scope="scope"
                >{{ scope.row.category_p ? scope.row.category_p.title : "" }}|{{
                  scope.row.category ? scope.row.category.title : ""
                }}</template
              >
            </el-table-column>
          </el-table>
        </div>
        <div class="main_page boxdq">
          <!-- 分页 -->
          <div></div>
          <div class="main_page_r">
            <MainPagination
              :current-page="current_sh.page"
              :page-sizes="[10, 30, 50, 100]"
              :page-size="limit_sh"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount_sh"
              background
              @size-change="changeLimit"
              @current-change="changePage"
            />
          </div>
          
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button @click="(shield = false), close()">取 消</el-button>
          <el-button type="primary" @click="shield_sh" v-repeatClick
            >确 定</el-button
          >
        </div>
      </el-dialog>

      <el-dialog
        title="商品导入"
        :visible.sync="importbuVisible"
        class="main_dialog dialog840 importbu"
      >
      <div class="dialog_padding20_30">
        <div class="importbu_p">
        <h3>导入说明：</h3>
        <p>1.注意使用红色字体标注的必填字段,不填或错填将导致导入失败。</p>
        <p>2.导入文件仅支持xlsx格式,大小不超过2M ,数据不超过2000行。</p>
        <p>3.导入文件不能包含“合并单元格”，否则无法导入。</p>
        <p>
          4.导入时碰到数据不正确的行，系统会跳过错误的行继续执行未完成的行。
        </p>
      </div>
      <div class="importbu_ul">
        <ul>
          <!-- <li>
            <p>已存在(非)标准库中</p>
            <el-radio-group v-model="import_form.goods_type" :border="true">
              <el-radio :label="1">自动从(非)标准库中导入</el-radio>
              <el-radio :label="2">跳过</el-radio>
            </el-radio-group>
          </li> -->
        </ul>
      </div>
      <div class="importbu_in">
        <h3>数据行区间设置</h3>
        <div class="box">
          <p>
            <span>第一个数据行号：</span
            ><el-input-number
              v-model="import_form.start_line_num"
              controls-position="right"
              :min="2"
            ></el-input-number>
          </p>
          <p>
            <span>最后一行数据行数：</span
            ><el-input
              v-model="import_form.end_line_num"
              placeholder="默认为全部"
              type="number"
            ></el-input>
          </p>
        </div>
      </div>
      <div class="importbu_an box">
        <el-button @click="downTemplate" class="marginRight10"
          >下载模板</el-button
        >
        <el-upload
          class="upload-demo"
          :action="groupGoodsBind_import"
          :on-success="importSuccess"
          :on-error="importerr"
          :show-file-list="false"
          :data="import_params"
          :headers="{
            Authorization: getToken(),
          }"
        >
          <el-button size="small" @click="handleUpload" type="primary"
            >点击上传</el-button
          >
        </el-upload>

        <p v-if="import_file_name ? true : false">
          上传文件名：{{ import_file_name }}
        </p>
      </div>
      <div class="import_process" v-if="percentShow">
        <div class="progress">
          <el-progress
            :text-inside="true"
            :stroke-width="20"
            :percentage="percent"
            color="#19B098"
          ></el-progress>
        </div>
        <div class="notice" v-if="percentShow">
          <div class="importtips">
            <p class="success" v-if="percent == 100">商品导入结束</p>
            <div v-for="(item, index) in reverseSum" :key="index">
              <p v-if="item.type == 2" :key="index" class="fail">
                {{ item.name }}，导入失败
              </p>
            </div>
          </div>
        </div>
      </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="cancelDisabled" @click="importbuVisible = false"
          >取 消</el-button
        >
      </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import {
  groupGoods_index,
  groupGoods_goods,
  groupGoods_bind,
  groupGoods_clean,
  groupGoods_cleanAll,
  groupGoods_bindImportModel
} from "@/api/user/userGroup";
import { puzzleImg,groupGoodsBind_import } from "@/api/currency";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { recursion, category } from "@/utils/index";
import { exportMethod } from "@/utils/index";

export default {
  computed: {
    ...mapGetters(["avatar"]),
  },
  data() {
    return {
      exportMethod,
      groupGoodsBind_import,
      // 筛选商品
      shield: false,
      form_sh: {
        pid: "",
        category_id: [],
        name: "",
      },
      current_sh: {
        page: 1,
        per_page: 10,
      },
      limit_sh: 10,
      totalCount_sh: 1,
      selectArr_sh: [],
      list_sh: {
        list: {
          data: [],
        },
      },
      // 分页
      current: {
        page: 1,
        per_page: 10,
      },
      limit: 20,
      totalCount: 1,
      // 搜索
      form: {
        name: "",
        pid: "",
        category_id: [],
      },
      // 更多
      moredata: false,
      // 列表数据
      list: {
        list: {
          data: [],
        },
      },
      puzzleImg,
      listLoading: false,
      // 全选
      selectArr: [],
      // 分类
      options: [],
      defaultProps: {
        children: "selfNext",
        label: "title",
        value: "id",
        checkStrictly: true,
      },
      // id
      id: this.$route.params.id,
       importbuVisible:false,
      import_form: {
        user_type: 1,
        goods_type: 1,
        start_line_num: 2,
        end_line_num: "",
      },
      import_file_name: "",
      import_params: {
        string: "",
        group_id:""
      },
      percent_gs: 0,
      percent: 0,
      percentShow: false,
      percent_list: [],
      importArrLength: 1,
      cancelDisabled: false,
    };
  },
  // 刷新
  inject: ["reload"],
  methods: {
    reset() {
      this.$refs['userListFrom'].resetFields();
      this.groupGoods_index();
    },
    // 关闭清空表单
    close() {
      this.$refs["userListFrom1"].clearValidate();
    },
    // 监听全选
    handleSelectionChange(val) {
      if (this.shield) {
        this.selectArr_sh = [];
        val.map((item) => {
          this.selectArr_sh.push({ id: item.id });
        });
      } else {
        this.selectArr = [];
        val.map((item) => {
          this.selectArr.push({ id: item.id });
        });
      }
    },
    // 筛选商品
    shield_sh() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { group_id: this.id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { group_id: this.id },
        { ids: JSON.stringify(this.selectArr_sh) }
      );
      if (this.selectArr_sh.length != 0) {
        groupGoods_bind(data).then((res) => {
          this.shield = false;
          if (res.errcode == 0) {
            this.$message({
              message: "筛选成功",
              type: "success",
            });
            this.reload();
          } else {
            this.$message.error(res.errmsg);
          }
        });
      } else {
        this.$message.error("请勾选商品");
      }
    },
    // 清空
    empty() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { group_id: this.id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { group_id: this.id }
      );
      groupGoods_cleanAll(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.$message({
            message: "清空成功",
            type: "success",
          });
          this.selectArr = [];
          this.selectArr_sh = [];
          this.$refs["userListFrom"].resetFields();
          if (this.$refs["userListFrom1"]) {
            this.$refs["userListFrom1"].resetFields();
          }
          this.current.page = 1;
          this.current_sh.page = 1;
          this.groupGoods_index();
          this.groupGoods_goods();
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    // 批量删除
    batch() {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { group_id: this.id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { group_id: this.id },
        { ids: JSON.stringify(this.selectArr) }
      );
      if (this.selectArr.length != 0) {
        groupGoods_clean(data).then((res) => {
          this.listLoading = false;
          if (res.errcode == 0) {
            this.$message({
              message: "删除成功",
              type: "success",
            });
            this.selectArr = [];
            this.selectArr_sh = [];
            this.$refs["userListFrom"].resetFields();
            if (this.$refs["userListFrom1"]) {
              this.$refs["userListFrom1"].resetFields();
            }
            this.current.page = 1;
            this.current_sh.page = 1;
            this.groupGoods_index();
            this.groupGoods_goods();
          } else {
            this.$message.error(res.errmsg);
          }
        });
      } else {
        this.$message.error("请勾选商品");
      }
    },
    // 搜索
    getArticleList() {
      if (this.shield) {
        this.current_sh.page = 1;
        this.groupGoods_goods();
      } else {
        this.current.page = 1;
        this.groupGoods_index();
      }
    },
    // 分页
    changeLimit(pageSize) {
      if (this.shield) {
        this.current_sh.per_page = pageSize;
        this.groupGoods_goods();
      } else {
        this.current.per_page = pageSize;
        this.groupGoods_index();
      }
    },
    changePage(page) {
      if (this.shield) {
        this.current_sh.page = page;
        this.groupGoods_goods();
      } else {
        this.current.page = page;
        this.groupGoods_index();
      }
    },
    // 列表
    groupGoods_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(
                apiUrl().name,
                this.list_form(),
                { group_id: this.id },
                this.current
              )
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { group_id: this.id },
        this.list_form(),
        this.current
      );
      groupGoods_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.options = recursion(res.data.categoryList, true);
          res.data.list.data.map((e) => {
            if (e.goods[0].images.length != 0) {
              e.goods[0].images.map((a) => {
                a.path = this.avatar.domain + a.path;
                if (a.main == 1) {
                  e.pic = a.path;
                }
              });
              e.pics = e.goods[0].images.map((s) => s.path);
            } else {
              e.pic = "";
              e.pics = [];
            }
          });

          this.list = res.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    groupGoods_goods() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(
                apiUrl().name,
                this.list_form(),
                { group_id: this.id },
                this.current_sh
              )
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { group_id: this.id },
        this.list_form(),
        this.current_sh
      );
      groupGoods_goods(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          res.data.list.data.map((e) => {
            if (e.images.length != 0) {
              e.images.map((a) => {
                a.path = this.avatar.domain + a.path;
                if (a.main == 1) {
                  e.pic = a.path;
                }
              });
              e.pics = e.images.map((s) => s.path);
            } else {
              e.pic = "";
              e.pics = [];
            }
          });
          this.list_sh = res.data;
          this.totalCount_sh = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.pid = form.category_id[0] ? form.category_id[0] : "";
      form.category_id = category(form.category_id);
      let form_sh = JSON.parse(JSON.stringify(this.form_sh));
      form_sh.pid = form_sh.category_id[0] ? form_sh.category_id[0] : "";
      form_sh.category_id = category(form_sh.category_id);

      return this.shield ? form_sh : form;
    },
        // 导入
    importDialog() {
      this.import_params.group_id=this.id
      this.import_file_name = "";
      this.percent_gs = 0;
      this.percent = 0;
      this.percentShow = false;
      this.percent_list = [];
      this.importArrLength = 1;
      this.cancelDisabled = false;
      this.importbuVisible = true;
    },
            // 下载模板
    downTemplate() {
      let form = {
        user_type: this.import_form.user_type,
        goods_type: this.import_form.goods_type,
      };
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        form
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      groupGoods_bindImportModel(data).then((res) => {
        this.exportMethod(res, "分组屏蔽商品导入模板", notify);
      });
    },
    importerr(err, file, fileList) {
      this.$message.error("上传失败");
    },
    importSuccess(response, file, fileList) {
      if (response.errcode != 0) {
        this.$message.error(response.errmsg);
        return;
      }
      this.import_file_name = file.name;
      this.$message.success("上传成功");
    },
    handleUpload() {
      this.import_params.string =
        this.import_form.start_line_num + "," + this.import_form.end_line_num;
      this.import_params.sign= Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.info, { id: this.id })
            ) + apiUrl().appsecret
          )
      this.import_params.timeStamp=Math.round(new Date().getTime()/1000)
    },
  },
  created() {
    // 列表
    this.groupGoods_index();
    this.groupGoods_goods();
  },
};
</script>
<style lang="scss" scoped>
/deep/.el-form-item--mini.el-form-item, .el-form-item--small.el-form-item {
  margin-bottom: 10px;
}
.mainor_form form {
  width: calc(100% - 280px);
}
.main_dialog .mainor_form form {
  width: calc(100% - 120px);
}
.main_dialog .main_table /deep/.el-checkbox {
  margin-bottom: 0;
}
.main_dialog .main_table {
  /deep/.el-table__body-wrapper {
    overflow-y: auto;
    height: 360px;
  }
}
.small-padding-dialog {
  .el-dialog__body {
    padding-top: 8px;
  }
}
</style>
